package com.zara.store.client.controller;

import java.math.BigDecimal;

import com.zara.store.client.clientmodel.RetailBasket;
import com.zara.store.client.clientmodel.RetailInvoice;
import com.zara.store.client.clientmodel.RetailModel;

import framework.clientmodel.Model;
import framework.controller.Controller;
import framework.view.View;

public class RetailController extends Controller {
	
	public RetailController(Model model, View view) {
		super(model, view);
	}

	public void addLine() {
		//TODO: si el producto ya se encuentra en la canasta, modificar la cantidad+1
		getRetailModel().addProduct();
	}
	
	public void changeLineAmount(int rowIndex, String amount) {
		try {
			Double.valueOf(amount);
		} catch(NumberFormatException e) { //validacion
			return;
		}
		BigDecimal newAmount = new BigDecimal(amount);
		RetailBasket model = modelAtIndex(rowIndex);
		BigDecimal currentAmount = model.getLineAmount();
		if(!newAmount.equals(currentAmount))
			getRetailModel().setLineAmount(newAmount);
	}
	
	public void changeLineOffer(int rowIndex) {
		RetailBasket model = modelAtIndex(rowIndex);
		boolean lineOffer = model.getLineOffer();
		boolean changedOffer;
		if(lineOffer) {
			changedOffer = false;
		} else {
			changedOffer = model.hasOfferPrice();
		}
		getRetailModel().setLineOffer(changedOffer);
	}

	public void removeLines(int[] rowIndexes) {
		if(rowIndexes!= null && rowIndexes.length>0) {
			getRetailModel().removeLines(rowIndexes);
		}
	}
	
	private RetailBasket modelAtIndex(int rowIndex) {
		RetailBasket model = getRetailModel().getBasketModel();
		model.changeRowIndex(rowIndex);
		return model;
	}

	// product
	
	public void queryProduct(String barcode) {
		getRetailModel().queryProduct(barcode);
	}
	
	// invoice

	public void createInvoice() {
		getRetailModel().createInvoice();
	}

	public void changeClientAddress(String value) {
		getInvoiceModel().setClientAddress(value);
	}

	private RetailInvoice getInvoiceModel() {
		return getRetailModel().getInvoiceModel();
	}

	public void changeInvoiceType(String value) {
		getInvoiceModel().setInvoiceType(value);
	}

	public void changeInvoiceTaxIVA(String value) {
		try {
			Double.valueOf(value);
		} catch(NumberFormatException e) { //validacion
			return;
		}
		BigDecimal bigDecimal = new BigDecimal(value);
		getInvoiceModel().setInvoiceTaxIVA(bigDecimal);
	}

	public void changeClientStatusIVA(String value) {
		getInvoiceModel().setClientStatusIVA(value);
	}

	public void changeClientName(String value) {
		getInvoiceModel().setClientName(value);
		
	}

	public void changeClientCUIT(String value) {
		getInvoiceModel().setClientCUIT(value);
	}

	private RetailModel getRetailModel() {
		return ((RetailModel) super.getModel());
	}

	public void newBasketAndInvoice() {
		getRetailModel().removeLines();
	}

}
